﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
using System.Configuration;

using Comswing.Website.Controllers;
using Comswing.Website.Models.BitcoinViewModels;

namespace Comswing.Website.Infrastructure
{
    public static class ProcessRunner
    {
        private static Timer _weightledPricesTimer;
        private static int _marketDataRefreshMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["MarketDataRefreshMinutes"]);
        private static double _marketDataRefreshTimeout = TimeSpan.FromMinutes(_marketDataRefreshMinutes).TotalMilliseconds;


        public static void Initialize()
        {
            FillBitcoinWeighledPrices();
            _weightledPricesTimer = new Timer(_marketDataRefreshTimeout);
            _weightledPricesTimer.Elapsed += new ElapsedEventHandler(FillBitcoinWeighledPricesHandler);
            _weightledPricesTimer.Enabled = true;
        }

        private static void RefreshHandler(object sender, ElapsedEventArgs e)
        {
        }

        public static void Refresh()
        {

        }

        private static void FillBitcoinWeighledPricesHandler(object sender, ElapsedEventArgs e)
        {
            FillBitcoinWeighledPrices();
        }

        private static void FillBitcoinWeighledPrices()
        {
            var bitcoinController = new BitcoinController();
            try
            {
                GlobalState.BitcoinState.WeightledPrices = bitcoinController.WeightedPrices();
                GlobalState.BitcoinState.LastUpdate = DateTime.Now;
                GlobalState.BitcoinState.RefreshTimeout = _marketDataRefreshTimeout;
            }
            catch
            {
                //keep the previous value
            }
        }
    }
}